<template>
  <div class="home">
    <!-- <img alt="Vue logo" src="../assets/logo.png"> -->
    <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
    <div class="main_body1" style="padding: 10px;">
      <div>
        <div class="content_top">
          <div class="row1">
            <div class="row1_1">
              <span class="text">可提现金额（元）</span>
              <!-- <text class="money">{{integral1 == NaN ? '0.00' : integral}}</text> -->
              <span class="money">{{withdrawable ? withdrawable : '0.00'}}</span>
            </div>
            <div id="myBtn" class="button" @click="modalinput()" v-if="tixian == 1">申请提现</div>
            <div id="myBtn" class="button1" @click="modalinput1()" v-if="tixian == 2">申请提现</div>
            <van-popup v-model="show">
              <div style="width:340px;height:100%;background:#fff;padding: 0 10px">
                <div class="choose">
                  <div style="font-size:40rpx;">选择银行卡/支付宝</div>
                </div>
                <van-radio-group v-model="radio" @change="radioChange">
                  <van-radio name="1" style="margin-bottom:10px;">
                    <div class="card" v-if="values == 1">
                      <div class="font">
                        <div class="popup">
                          <van-icon name="debit-pay" size="24" />
                          <!-- <div class="text">银行名字</div> -->
                          <div class="text">{{bankName}}</div>
                        </div>
                        <!-- <div>银行账号</div> -->
                        <div>{{bankCardNum}}</div>
                        <!-- <div>真实姓名</div> -->
                        <div>{{trueName}}</div>
                      </div>
                      <div>
                        <div class="pass">审核通过</div>
                      </div>
                    </div>
                  </van-radio>
                  <van-radio name="2">
                    <div class="card" v-if="values == 1">
                      <div class="font">
                        <div class="popup">
                          <van-icon name="gold-coin-o" size="22"/>
                          <div class="text">支付宝</div>
                        </div>
                        <!-- <div>支付宝账号</div> -->
                        <div>{{aliPayAccount}}</div>
                        <!-- <div>真实姓名</div> -->
                        <div>{{trueName}}</div>
                      </div>
                      <div>
                        <div class="pass">审核通过</div>
                      </div>
                    </div>
                  </van-radio>
                </van-radio-group>
                <div class="confirm" @click="confirmClick" data-xxx="xxx">确认提现</div>
              </div>
            </van-popup>
          </div>
          <div class="row2"></div>
        </div>
        <div class="line"></div>
        <div class="content_bottom">
          <div class="content_bottom_view" @click="toEarningsRecord()">
            <span class="span">收益记录</span>
            <van-icon name="arrow" />
          </div>
          <div class="line"></div>
          <div class="content_bottom_view" @click="toWithdrawalHistory()">
            <span class="span">提现记录</span>
            <van-icon name="arrow" />
          </div>
          <div class="line"></div>
          <div class="content_bottom_view" @click="toPayCard()">
            <span class="span">银行卡/支付宝</span>
            <van-icon name="arrow" />
          </div>
          <div class="line"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
var utils = require("../../utils/utils");
var baseConfig = require("../utils/baseConfig");
// import HelloWorld from '@/components/HelloWorld.vue'
import Vue from 'vue';
import { Dialog, Icon, Popup, Radio, RadioGroup, Toast } from 'vant';

Vue.use(Dialog);
Vue.use(Icon);
Vue.use(Popup);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Toast);

export default {
  name: "Home",
  components: {
    // HelloWorld
  },
  data() {
    return {
      show: false,
      // hiddenmodalput: true,
      // hidden: true, //可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
      tixian: 1,
      radio: '1',
      values: 1,
      totalIncomes: '',
      withdrawable: '',
      sumEarnings: '',
      bankName: '',
      bankCardNum: '',
      aliPayAccount: '',
      trueName: '',
      status: '',
      is_weixin: '2',
      priceType: 'cpm',
      code: '',
    }
  },
  created() {
    // this.init();
    // this.get_earnings_record_data();
    // this.get_bank_alipay_list()
    // this.getDateData();
  },
  mounted() {
    if(!window.localStorage.getItem('code')){ // 如果缓存localStorage中没有微信openId，则需用code去后台获取
      this.getCode();
    } else {
      console.log('123');
      this.get_bank_alipay_list()
      this.getDateData();
    }
  },
  methods: {
    getCode () { // 非静默授权，第一次有弹框
      this.code = '';
      var local = window.location.href;// 获取页面url
      // console.log(loacl);
      var appid = 'wxb0f1d9c0eb3e809c';
      this.code = this.getUrlCode().code; // 截取code
      console.log(this.code);
      if (this.code == null || this.code === '') { // 如果没有code，则去请求
          console.log('000');
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=https://gv.tuiwa.com&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
      } else {
          console.log('111');
          localStorage.setItem('code', this.code);
          console.log('222');
          this.login();
          console.log('333');
      }
    },
    getUrlCode() { // 截取url中的code方法
      var url = location.search
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&")
        for(var i = 0; i < strs.length; i ++) {
          theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
        }
      }
        // console.log(theRequest);
        // this.code = theRequest.code;
        return theRequest
    },
    getToken() { // 获取token
      let appid = 'wxb0f1d9c0eb3e809c';
      let secret = '521fe445781a7132769a465eafa8c239';
      let code = localStorage.getItem("code");
      // window.location.href = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`;
      // 得到 access_token, openid
      let wxLoginInfo = this.$http.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`).body;

      console.log(wxLoginInfo);
      let { access_token, openid } = wxLoginInfo;
      console.log(access_token, openid);
      // 得到 用户信息
      let wxUserInfo = this.$http.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`).body;
      console.log(wxUserInfo);

      let { nickname, unionid, headimgurl } = wxUserInfo;
      console.log(nickname, unionid, headimgurl);

      localStorage.setItem('wxUserInfo', JSON.stringify(wxUserInfo));
      localStorage.setItem('unionid', unionid);
      this.login();
    },
    login() {  // 获取用户信息
      console.log('login');
      let appid = 'wxb0f1d9c0eb3e809c'; // 公众号appid
      let code = localStorage.getItem('code');
      let data = {
        "code": code,
        "appId": appid
      }
      this.$http.post(`${baseConfig.baseUrl}wxgzh/get_user_by_unionId`, data, {
          headers: {
              'Content-Type':'application/json'
          },
      })
        .then(
          res => {
            console.log(res.data.data);
            if (res.data.data == '' || res.data.data == undefined) {
              Toast.fail('登录失败，请重新登录');
            } else {
              localStorage.setItem('userInfo',JSON.stringify(res.data.data));
              this.get_bank_alipay_list()
              this.getDateData();
            }
          }
      )
    },
    radioChange() { // 选择提现方式
      // console.log('radio发生change事件，携带value值为：', this.radio)
      if(this.radio == 1) {
        console.log('支付方式为银行卡')
      } else if(this.radio == 2) {
        console.log('支付方式为支付宝')
      }
    },
    modalinput() { // 暂无支付方式
      console.log('申请提现data', this.$data);
      Dialog.confirm({
        title: '温馨提示',
        message: '您还没有补充您的银行卡/支付宝信息，为避免提现失败，请尽快补充相关信息。（若显示仍在审核，请耐心等待）',
        confirmButtonText: '前往确认',
      })
        .then(() => {
          this.$router.push('/kstoPayCard');
        })
        .catch(() => {
          console.log('点击取消');
        });
    },
    modalinput1() { // 已有支付方式
      this.show = true;
      this.radioChange()
    },
    confirmClick() { // 点击提现
      this.show = false;
      console.log(this.radio);
      Dialog.confirm({
        title: '温馨提示',
        message: '确认提现全部余额吗？',
      })
        .then(() => {
          Dialog.alert({
            message: '提现成功，预计十五个工作日内到账',
            confirmButtonText: '知道了',
          }).then(() => {
            console.log('提现成功');
          });
        })
        .catch(() => {
          console.log('取消提现');
        });
    },
    toEarningsRecord() { // 前往收益记录
      this.$router.push('/toEarningRecord');
    },
    toWithdrawalHistory() { // 前往提现记录
      this.$router.push('/kstoWithdrawalHistory');
    },
    toPayCard() { // 前往添加支付方式
      this.$router.push('/kstoPayCard');
    },
    async getData() {
      await this.get_earnings_record_data()
    },
    get_bank_alipay_list() { // 获取已登记的支付方式
      // let loginUserId = 'ohI6C4tTiL0skHDt-FaRfOnBMkI0';
      // let uid = 146;
      let loginUserId = JSON.parse(localStorage.getItem('userInfo')).openid;
      let uid = JSON.parse(localStorage.getItem('userInfo')).id;
      this.$http.post(`${baseConfig.url}tuiwaApp/get_bank_alipay_list?loginUserId=` + loginUserId
       + '&uid=' + uid)
        .then(
          res => {
            console.log(res.data);
            console.log(res.data.data[0]);
            if (res.data.code == 200) {
                if (res.data.data[0].status == 0){
                  // console.log('00000000');
                } else if(res.data.data[0].status == 1) {
                  this.bankName = res.data.data[0].bankName
                  this.bankCardNum = res.data.data[0].bankCardNum.replace(/\s/g, '').replace(/(\d{4})\d+(\d{4})$/, "**** **** **** $2") // 将银行卡号前部分用 * 代替，仅显示后四位
                  this.aliPayAccount = res.data.data[0].aliPayAccount
                  this.trueName = res.data.data[0].trueName
                  // this.accountType= res.data.data[0].accountType
                  if (this.aliPayAccount || this.bank) {
                    this.tixian = 2;
                    // console.log(this.tixian);
                  }
                }
            } else {
                return false;
            }
          }
        )
    },
    get_earnings_record_data() { // 获取收益信息
      // let loginUserId = 'ohI6C4tTiL0skHDt-FaRfOnBMkI0';
      // let uid = 146;
      let loginUserId = JSON.parse(localStorage.getItem('userInfo')).openid;
      let uid = JSON.parse(localStorage.getItem('userInfo')).id;
      this.$http.post(`${baseConfig.url}tuiwaApp/get_earnings_record_data?loginUserId=` + loginUserId
        + '&uid=' + uid
        + '&start_time=' + this.start_time
        + '&end_time=' + this.end_time
        + '&is_weixin=' + this.is_weixin
        + '&priceType=' + this.priceType
      )
        .then(res => {
          console.log(res.data.data);
          // this.sumEarnings = res.data.data.sumEarnings;
          this.withdrawable = (res.data.data.sumEarnings - res.data.data.yigeiEarnings).toFixed(2);
        })
    },
    getDateData: function () { // 进入页面默认年月
      var timestamp = Date.parse(new Date());
      var date = new Date(timestamp);
      var Y = date.getFullYear(); // 获取年 
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); // 获取月
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); // 获取日
      const yearMonth = Y + '-' + M;
      // console.log(yearMonth);
      // 暂无用处
      this.yearMonth = yearMonth
      this.date = yearMonth
      this.year = Y
      this.month = M
      this.day = D
      // 暂无用处
      this.getMonthFirstLastDay(Y, M)
    },
    getMonthFirstLastDay(year, month) {
      var firstDay = new Date(year, month - 1, 1); //这个月的第一天
      var currentMonth = firstDay.getMonth(); //取得月份数
      var lastDay = new Date(firstDay.getFullYear(), currentMonth + 1, 0); //是0而不是-1
      let start_time = utils.formatDate(firstDay, 'yyyy-mm-dd')
      let end_time = utils.formatDate(lastDay, 'yyyy-mm-dd')
      this.start_time = start_time;
      this.end_time = end_time;
      // console.log('start_end_time', this.yearMonth, this.start_time, this.end_time)
      this.getData();
    },
    init() { // 获取已有金额(暂定)
      // let uid = 146;
      let uid = JSON.parse(localStorage.getItem('userInfo')).id;
      this.$http.get(`${baseConfig.baseUrl}users/simpleInfo?uid=` + uid)
        .then(res => {
          console.log(res.data.data);
          // this.totalIncomes = res.data.data.totalIncomes
        })
    },
  },
};
</script>

<style scoped>
/* 静态页基本样式 */
.content_top {
  padding: 16px 13px;
}

.icon {
  font-weight: bold;
  margin-right: 10px;
}

.content_top .list {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 0 0 33.3%;
}

.content_top .row1 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.content_top .row1 .row1_1 {
  display: flex;
  flex-direction: column;
  margin-top: 16px;
}

.content_top .row1 .row1_1 .text {
  font-size: 18px;
  font-weight: bolder;
  color: #737C84;
}

.content_top .row1 .row1_1 .money {
  font-size: 30px;
  font-weight: 500;
  color: #1c1a1a;
  /* margin-left: 15px; */
}

.button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 106px;
  height: 34px;
  font-size: 14px;
  font-weight: 500;
  background: #86898c;
  color: #f9f6f5;
  border: 1px solid #DA8E57;
  border-radius: 5px;
  margin: 22px 18px 0 0;
}

.button1 {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 106px;
  height: 34px;
  font-size: 14px;
  font-weight: 500;
  background: #49ccc3;
  color: #f9f6f5;
  border: 1px solid #DA8E57;
  border-radius: 5px;
  margin: 22px 18px 0 0;
}

.content_top .row2 {
  display: flex;
  flex-grow: 1;
  align-items: center;
}

.content_top .row2 .list .text1 {
  font-size: 22px;
  color: #1c1a1a;
}

.content_top .row2 .list .text2 {
  font-size: 12px;
  color: #737C84
}

.line {
  margin: 15px 0;
  border: 1px solid #6C6F75
}

.content_bottom .content_bottom_view {
  display: flex;
  justify-content: space-between;
}

.content_bottom .span {
  font-size: 18px;
  color: #737C84;
  margin-left: 10px;
}

.content_bottom .text {
  font-size: 18px;
  color: #737C84;
  margin-right: 10px;
}

/* （弹出框）选择银行卡或者支付宝 */
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
  background-color: rgba(20, 23, 43, 0.6);
}

.content_container {
  width: 80%;
  height: 540px;
  border-radius: 20px;
  background-color: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.content_wrapper {
  padding: 10px;
}

.close {
  width: 24px;
  height: 24px;
  position: fixed;
  bottom: 230px;
  left: 175px;
}

.close .iconfont {
  font-size: 28px;
  color: #fff;
}

.popup.iconfont {
  font-size: 24px;
  color: #fff;
}

.choose {
  display: flex;
  flex-direction: column;
  margin: 15px 0;
  text-align: center;
  font-weight: bolder;
}

.confirm {
  width: 150px;
  height: 40px;
  line-height: 40px;
  background: #49ccc3;
  color: #fff;
  font-size: 16px;
  display: block;
  margin: 20px auto;
  text-align: center;
  border-radius: 5px;
}

.main {
  display: flex;
  flex-direction: column;
  height: 330px;
}

.radio {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.radio-group {
  display: flex;
  flex-direction: column;
}

.card {
  width: 280px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border: 1px solid #fff;
  background: #354EE3;
  padding: 10px;
  margin-left: 5px;
  margin-bottom: 5px;
}

.font {
  font-size: 14px;
  color: #fff;
  text-align: left;
}

.font .popup {
  display: flex;
  flex-direction: row;
}

.text {
  line-height: 25px;
  margin-left: 5px;
}

.pass {
  color: #fff;
  font-size: 12px;
}
</style>
